// packageA/pages/cashService/admin/personManage/personManage.js
const { request } = require('../../../../utils/request');
const { imgPath } = require('../../../../utils/request');
const { encryptSM2, decryptSM4 } = require('../../../../utils/sm-crypto');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgPath: imgPath,
    searchKey: '',
    startId: '',
    dropdownValue: '',
    showCodeInput:false,
    dropdownOptions: [
      { text: '全部', value: '' },
      { text: '启用', value: 'Y' },
      { text: '停用', value: 'N' },
    ],
    station: '',
    userList: [],
    userListFinished: false,
    batchDeleteFlag: false,
    result: [],
    mode: 'user',
    searchKey2: '',
    startId2: '',
    abstractList: [],
    abstractListFinished: false,
    batchDeleteFlag2: false,
    result2: [],
    ifShowSetting: false,
    showPwdDialog: false,
    oldPwd: '',
    pwd: '',
    pwd2: '',
    pwdInfo: '',
    btnDisable: true,
    captchaData: {},
    post:'', //员工list类型
    loginType:'',
    changeStaffId:'' , //修改密码的员工id
    staffCode:'',  //员工修改密码
    showDeleteConfirm:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '人员管理',
    })
    let tempStation = '';
    if(wx.getStorageSync('userInfo').loginType == 3){
      tempStation = '企业管理员'
    }else if(wx.getStorageSync('userInfo').loginType == 2){
      tempStation = wx.getStorageSync('userInfo').stationNo + '-' + wx.getStorageSync('userInfo').stationName;
    }

    this.setData({ 
      station: tempStation,
      loginType:wx.getStorageSync('userInfo').loginType
    })
    //post控制员工列表的筛选
    if(this.data.loginType == '3'){
      this.setData({
        post:'站点管理员,站点操作员'
      })
    }else if(this.data.loginType == '2'){
      this.setData({
        post:'站点操作员'
      })
    }
  },
  onShow() {
    this.setData({
      startId: '',
      userListFinished: false,
      userList: [],
      startId2: '',
      abstractList: [],
      abstractListFinished: false
    })
    this.fetchOperatorList()
    if(this.data.loginType == '2'){
      this.fetchAbsList()
    }
  },

  /**
   * 获取操作员列表
   */
  fetchOperatorList() {
    if (this.data.userListFinished) {
      return
    }
    const key = '4f39f20ec1fd479fa6dc3fd2d353d47d'
    let timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    let queryData = {
      staffName: this.data.searchKey,
      enableFlag: this.data.dropdownValue,
      startId: this.data.startId,
      post: this.data.post,
      staffType: 1, // 1公司 2三方
      timestamp: timestamp
    }
    request('/smsk/wechat/staff/query', 'GET', queryData).then(res => {
      if (res.data.code == 0) {
        if (res.data.data.length === 0) {
          this.setData({
            userListFinished: true
          })
        } else {
          let tempList = this.data.userList
          res.data.data.forEach(item => {
            item.idNum = decryptSM4(item.idNum, key)
            item.staffName = decryptSM4(item.staffName, key)
            item.phoneNum = decryptSM4(item.phoneNum, key)
            tempList.push(item)
          })
          this.setData({
            userList: tempList,
            startId: res.data.data[res.data.data.length - 1].id
          })
        }
      }
    })
  },
  /**
   * 搜索操作员列表
   */
  onSearch(e) {
    this.setData({
      searchKey: e.detail,
      startId: '',
      userListFinished: false,
      userList: []
    })
    this.fetchOperatorList()
  },
  showDeleteCof(e){
    console.log(e.currentTarget.id,'staffid')
    this.setData({
      showDeleteConfirm:true,
      changeStaffId:e.currentTarget.id
    })
  },
  showPwdInput(e){
    console.log(e.currentTarget.id,'staffid')
    this.setData({
      showCodeInput:true,
      changeStaffId:e.currentTarget.id,
      staffCode:'smskSTAFF!1'
    })
    this.fetchCaptcha()
  },
  changeStaffPwd(e){
    let query = {
      id: this.data.changeStaffId,
      newPasswd:encryptSM2(this.data.staffCode, this.data.captchaData.publicKey),
      captchaId: this.data.captchaData.captchaId,
      encrypted: true
    }
    request('/smsk/wechat/staff/passwd/change', 'POST', query).then(res => {
      // console.log(res.data)
      if (res.data.code == 0) {
        wx.showToast({
          title: '更新成功',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
      }
    })
  },
  /**
   * 取消搜索操作员列表
   */
  onCancel() {
    this.setData({
      searchKey: '',
      startId: '',
      userListFinished: false,
      userList: []
    })
    this.fetchOperatorList()
  },
  /**
   * 解锁员工
   */
  handleUnlock(e){
    request('/smsk/wechat/staff/unlock?staffId='+e.currentTarget.id, 'POST').then(res => {
      // console.log(res.data)
      if (res.data.code == 0) {
        wx.showToast({
          title: '更新成功',
          icon: 'success'
        })
        this.setData({
          startId: '',
          userListFinished: false,
          userList: []
        })
        this.fetchOperatorList()
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
      }
    })
  },
  /**
   * 操作员下拉筛选状态
   */
  dropdownSelect(e) {
    this.setData({
      dropdownValue: e.detail,
      startId: '',
      userListFinished: false,
      userList: []
    })
    this.fetchOperatorList()
  },
  /**
   * 修改操作员状态
   */
  handleStatus(e) {
    console.log(e.currentTarget.dataset.index)
    let query = {
      id: this.data.userList[e.currentTarget.dataset.index].id
    }
    request('/smsk/wechat/staff/status', 'POST', query).then(res => {
      // console.log(res.data)
      if (res.data.code == 0) {
        let tempStr = 'userList[' + e.currentTarget.dataset.index + '].enableFlag'
        this.setData({
          [tempStr]: res.data.data
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
      }
    })
  },
  /**
   * 人员管理点击“批量删除”
   */
  batchDelete() {
    this.setData({
      batchDeleteFlag: true,
      result: []
    });
  },
  /**
   * 批量删除取消
   */
  cancelDelete() {
    this.setData({
      batchDeleteFlag: false,
      result: []
    });
  },
  /**
   * 删除操作员
   */
  handleDelete() {
    let queryData = []
    if (this.data.batchDeleteFlag) {
      // 批量删除
      queryData = this.data.result
    } else {
      // 单个删除
      queryData.push(this.data.changeStaffId)
    }
    request('/smsk/wechat/staff/delete', 'POST', { ids: queryData }).then(res => {
      // console.log(res.data)
      if (res.data.code == 0) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        })
        this.setData({
          startId: '',
          userListFinished: false,
          userList: []
        })
        this.fetchOperatorList()
      }
    })
    this.setData({
      batchDeleteFlag: false,
      result: []
    });
  },
  /**
   * 新增操作员/编辑操作员
   */
  addPerson(e) {
    let tempData = ''
    if (this.data.userList[e.currentTarget.dataset.index]) {
      tempData = JSON.stringify(this.data.userList[e.currentTarget.dataset.index])
    }
    console.log(e)
    wx.navigateTo({
      url: '/pages/cashService/admin/addPerson/addPerson?data=' + tempData,
    })
  },
  /**
   * 人员多选（点击checkbox）
   */
  onChange(e) {
    this.setData({
      result: e.detail,
    });
  },
  /**
   * 人员多选（点击名字）
   */
  onChange2(e) {
    if (this.data.batchDeleteFlag) {
      let tempid = this.data.result.indexOf(e.currentTarget.id)
      if (tempid == -1) {
        let temp = this.data.result
        temp.push(e.currentTarget.id)
        this.setData({
          result: temp
        })
      } else {
        let temp = this.data.result
        temp.splice(tempid, 1)
        this.setData({
          result: temp
        })
      }
    }
  },

  /**
   * 切换管理项目
   */
  modeChange(e) {
    this.setData({
      mode: e.currentTarget.dataset.mode
    })
    if (this.data.mode == 'user') {
      wx.setNavigationBarTitle({
        title: '人员管理',
      })
    } else {
      wx.setNavigationBarTitle({
        title: '缴款项目管理',
      })
    }
  },
  /**
   * 登出
   */
  logout() {
    request('/smsk/wechat/auth/logout', 'POST').then(res => {
      console.log(res.data)
      if (res.data.code == 0) {

        wx.setStorageSync('userInfo', res.data.data)
        wx.setStorageSync('token', res.data.data.token)
        wx.redirectTo({
          url: '/pages/cashService/roleSelection/roleSelection',
        })
      } else {
        this.showToast(res.data.message)
      }
    })
  },

  /**
   * 获取款项列表
   */
  fetchAbsList() {
    if (this.data.abstractListFinished) {
      return
    }
    let queryData = {
      fundName: this.data.searchKey2,
      startId: this.data.startId2
    }
    request('/smsk/wechat/fundsource/query', 'GET', queryData).then(res => {
      console.log(res.data)
      if (res.data.code == 0) {
        if (res.data.data.length === 0) {
          this.setData({
            abstractListFinished: true
          })
        } else {
          let tempList = this.data.abstractList
          res.data.data.forEach(item => {
            tempList.push(item)
          })
          this.setData({
            abstractList: tempList,
            startId2: res.data.data[res.data.data.length - 1].id
          })
        }
      }
    })
  },
  /**
   * 搜索款项列表
   */
  onSearch2(e) {
    this.setData({
      searchKey2: e.detail,
      startId2: '',
      abstractListFinished: false,
      abstractList: []
    })
    this.fetchAbsList()
  },
  /**
   * 取消搜索款项列表
   */
  onCancel2() {
    this.setData({
      searchKey2: '',
      startId2: '',
      abstractListFinished: false,
      abstractList: []
    })
    this.fetchAbsList()
  },
  /**
   * 点击批量删除款项列表
   */
  batchDelete2() {
    this.setData({
      batchDeleteFlag2: true,
      result2: []
    });
  },
  /**
   * 取消批量删除款项列表
   */
  cancelDelete2() {
    this.setData({
      batchDeleteFlag2: false,
      result2: []
    });
  },
  /**
   * 删除缴款项目
   */
  handleDelete2(e) {
    let queryData = []
    if (this.data.batchDeleteFlag2) {
      // 批量删除
      queryData = this.data.result2
    } else {
      // 单个删除
      queryData.push(this.data.abstractList[e.currentTarget.dataset.index].id)
    }
    request('/smsk/wechat/fundsource/delete', 'POST', { ids: queryData }).then(res => {
      // console.log(res.data)
      if (res.data.code == 0) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        })
        this.setData({
          startId2: '',
          abstractListFinished: false,
          abstractList: []
        })
        this.fetchAbsList()
      }
    })
    this.setData({
      batchDeleteFlag2: false,
      result2: []
    });
  },
  /**
   * 缴款项目多选（checkbox）
   */
  onChange3(e) {
    this.setData({
      result2: e.detail,
    });
  },
  /**
   * 缴款项目多选（点击名字）
   */
  onChange4(e) {
    if (this.data.batchDeleteFlag2) {
      let tempid = this.data.result.indexOf(e.currentTarget.id)
      if (tempid == -1) {
        let temp = this.data.result2
        temp.push(e.currentTarget.id)
        this.setData({
          result2: temp
        })
      } else {
        let temp = this.data.result2
        temp.splice(tempid, 1)
        this.setData({
          result2: temp
        })
      }
    }
  },
  /**
   * 缴款项目新增/编辑
   */
  addAbst(e) {
    let tempData = ''
    if (this.data.abstractList[e.currentTarget.dataset.index]) {
      tempData = JSON.stringify(this.data.abstractList[e.currentTarget.dataset.index])
    }
    wx.navigateTo({
      url: '/pages/cashService/admin/addAbst/addAbst?data=' + tempData,
    })
  },
  closeSetting() {
    this.setData({ ifShowSetting: false })
  },
  showSetting() {
    this.setData({ ifShowSetting: !this.data.ifShowSetting })
  },

  showPwdChange() {
    this.setData({
      ifShowSetting: !this.data.ifShowSetting,
      showPwdDialog: true,
      oldPwd: '',
      pwd: '',
      pwd2: ''
    })
    // 获取
    this.fetchCaptcha()
  },
  onClose() {
    this.setData({ showPwdDialog: false })
  },
  checkPwd() {
    this.setData({ pwdInfo: '', btnDisable: true })
    if (this.data.pwd && this.data.pwd2) {
      if (this.data.pwd != this.data.pwd2) {
        this.setData({ pwdInfo: '两次输入密码不同' })
      } else if (this.data.oldPwd) {
        this.setData({ btnDisable: false })
      }
    }
  },
  changePwd() {
    if (this.data.btnDisable) {
      return
    }
    let query = {
      oldpasswd: encryptSM2(this.data.oldPwd, this.data.captchaData.publicKey),
      newpasswd: encryptSM2(this.data.pwd, this.data.captchaData.publicKey),
      captchaId: this.data.captchaData.captchaId,
      encrypted: true
    }
    request('/smsk/wechat/auth/passwd', 'POST', query).then(res => {
      // console.log(res.data) 
      this.fetchCaptcha()
      if (res.data.code == 0) {
        wx.showToast({
          title: '修改成功',
          icon: 'success'
        })
        this.setData({ 
          showPwdDialog: false,
          oldPwd: '',
          pwd: '',
          pwd2: ''
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
      }
    })
  },
  fetchCaptcha() {
    request('/smsk/wechat/auth/captchaw150h30', 'GET').then(res => {
      this.setData({
        captchaData: res.data.data
      })
    })
  },
  /**
   * 跳转查看订单
   */
  toOrderPage(){
    wx.navigateTo({
      url: '/pages/cashService/admin/order/order'
    })
  }
})